package com.umfwechat.h5.controller.sign;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.ConfigConsts;
import com.umfwechat.common.constant.MsgConsts;
import com.umfwechat.common.constant.ValueConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.util.DateTimesUtil;
import com.umfwechat.util.HttpHelper;
import com.umfwechat.util.PropertyUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.RequestUtil;
import com.umfwechat.util.ResultJsonUtil;
import com.umfwechat.util.SaasPropertyUtil;
import com.umfwechat.util.SmsCheckUtil;
import com.umfwechat.util.StringUtil;
import com.umpay.operation.model.edrawInf.EdrawInf;
import com.umpay.operation.model.merchant.Protocol;
import com.umpay.operation.model.offlinepay.tfilingmer.MerBankInf;
import com.umpay.operation.model.product.MerProduct;
import com.umpay.operation.service.edrawInf.remote.EdrawInfServiceRemote;
import com.umpay.operation.service.offlinepay.tfilingmer.BankInfServiceRemote;
import com.umpay.operation.service.product.MerProductServiceRemote;
import com.umpay.operation.service.spapplyplat.remote.JoinFlowServiceRemote;
import com.umpay.operation.util.CommonUtils;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.AppChannel;
import com.umpay.sp.model.saas.StoreInf;
import com.umpay.sp.service.saas.remote.AppChannelServiceRemote;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.service.sys.remote.UserServiceRemote;
import com.umpay.sp.util.SequenceUtil;
import com.umpay.sp.xml.XmlData;
import com.umpay.util.HttpUtil;


/**
 * @desc  签约模块
 * @author Wangzhilong
 * @date 2017-5-11 下午5:27:31
 */
@Controller
@RequestMapping("/h5/sign")
public class SignController {

	private static Logger logger = LoggerFactory.getLogger(SignController.class);
	
	@Resource
	private UserServiceRemote userServiceRemote_sp; 
	@Resource
	private AppChannelServiceRemote appChannelServiceRemote; 
	//店铺部署接口
	@Resource
	private StoreInfServiceRemote storeInfServiceRemot;
	@Resource
	private MerProductServiceRemote merProductServiceRemote;//添加商户产品关系
	
	@Resource
	private BankInfServiceRemote bankInfServiceRemote;

	// 查询银行账户信息的接口
	@Resource
	private EdrawInfServiceRemote edrawInfRemote;
	@Resource
	private JoinFlowServiceRemote joinFlowServiceRemote;
	/**
	 * 首次签约页面初始化
	 * @param session
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/receiver/getStoreBySign",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String getStoreBySign(HttpServletRequest request, HttpServletResponse response) throws Exception{		
		logger.info("首次签约初始化页面接口开始=======>>>>|SignController|getStoreBySign");
		
		String openid="";
		if(request.getSession().getAttribute("openid") != null){
			openid = request.getSession().getAttribute("openid").toString();//获取openid
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> result = new HashMap<String, Object>();
		
		if(StringUtil.isEmpty(openid)){
			resultMap.put("retCode", RetCode.FAIL);
			logger.info("从session中获取openid获取失败！");
			return JSONObject.fromObject(resultMap).toString();
		}
		//立马付产品编号
		String productId = PropertyUtil.getProperties("umfWeChatPlat_appConf.properties").getProperty("productId_impay");
		if(StringUtil.isEmpty(productId)){
			resultMap.put("retCode", RetCode.FAIL);
			logger.info("获取property获取失败！");
			return JSONObject.fromObject(resultMap).toString();
		}
		//立马付主产品编号
		String mainProductId = PropertyUtil.getProperties("umfWeChatPlat_appConf.properties").getProperty("mainProductId");
		if(StringUtil.isEmpty(mainProductId)){
			resultMap.put("retCode", RetCode.FAIL);
			logger.info("获取mainProductId获取失败！");
			return JSONObject.fromObject(resultMap).toString();
		}
		
		try{
			//根据opendi查询第三方网站用户的用户编号
			ReqMessage req1 = ReqMessageUtil.makeSpReq();
			req1.getReqMap().put("externaluserId", openid);
			
			logger.info("查询第三方网站用户接口开始 ：【1】【1】【1】【1】req1=" + req1);
		    ResMessage res1 = userServiceRemote_sp.queryUserBind(req1);
			logger.info("查询第三方网站用户接口结束 ：【1】【1】【1】【1】resMessage=" + res1.getRetCode());

			
			if(!res1.getRetCode().equals(RetCode.SUCCESS)){ //判断res1
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg", res1.getRetMsg());
				logger.info("查询第三方网站用户接口 失败:【失败】 "+res1.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}
			if("".equals(res1.getResMap().get("userId"))||res1.getResMap().get("userId")==null){//未取到用户编号
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","未获取到用户编号");
				logger.info("查询第三方网站用户接口 失败 ：【未获取到用户编号】" +res1.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}
			String userId = res1.getResMap().get("userId").toString();//用户编号
			
			//根据主键userId查询用户详情接口
			ReqMessage req2 = ReqMessageUtil.makeSpReq();
			req2.getReqMap().put("userId", userId);
			logger.info("查询用户详情接口开始 ：【2】【2】【2】【2】req2=" + req2);
			ResMessage res2 = userServiceRemote_sp.getUserByIdSaaS(req2);
			logger.info("查询用户详情接口结束 ：【2】【2】【2】【2】res2=" + res2);
			//判断查询用户详情是否成功
			if(!res2.getRetCode().equals(RetCode.SUCCESS)){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg",res2.getRetMsg());
				logger.info("查询用户详情接口 失败：【失败】" +res2.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}
			//获取用户详情
			Map<String,Object> map =(Map<String,Object>)res2.getValue("merUser");
			String mediaId = map.get("merId").toString();////收款人的主商户
			String name = map.get("name").toString();//用户名
			if(mediaId==null||"".equals(mediaId)){//未取到商户号
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","未取到商户号");
				logger.info("查询用户详情接口 失败：【未取到商户号】"+res2.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}
			if(!"0".equals(map.get("state").toString())){//用户不可用
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","用户不可用号");
				logger.info("查询用户详情接口 失败：【用户不可用号】" +res2.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}
			//店铺部署详情列表接口
			ReqMessage req3 = ReqMessageUtil.makeSpReq();
			req3.getReqMap().put("merId", mediaId);
			req3.getReqMap().put("registerProcsStates","'05','06','07','08','09','10'");
			logger.info("店铺部署详情列表接口开始 ：【3】【3】【3】【3】req3=" + req3);
			ResMessage res3 = storeInfServiceRemot.getStoreInfList(req3);
			logger.info("店铺部署详情列表接口结束 ：【3】【3】【3】【3】resMessage=" + res3.getRetCode());
			if(!res3.getRetCode().equals(RetCode.SUCCESS)){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg",res3.getRetMsg());
				logger.info("店铺部署详情列表接口失败 ：【res3】【失败】"+res3.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}
			String totalSize = res3.getResMap().get("totalSize").toString();//店铺数量
			logger.info("店铺部署详情列表接口 查询出的数量：【res3】【totalSize】"+totalSize);
			if("0".equals(totalSize)){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","用户未开通店铺");
				logger.info("店铺部署详情列表接口 ：【res3】【用户未开通店铺】"+res3.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}
			// 读取店铺部署详情列表中的店铺列表
			List<StoreInf> list = (List<StoreInf>)res3.getValue("storeInfList");
			for (StoreInf storeInf : list) {
				
				String productId_add = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PRODUCTID_IMPAY_ADDED);
				// 渠道开通列表返回查询接口
				ReqMessage req5 = ReqMessageUtil.makeSpReq();
				req5.getReqMap().put("appSysId",storeInf.getStoreId());
				req5.getReqMap().put("productIds","'"+productId+"','"+productId_add+"'");
				logger.info("根据主键查询渠道表开始 ：【5】【5】【5】【5】req5 = " + req5);
				ResMessage res5 =appChannelServiceRemote.getAppChannelListByProductids(req5);
				logger.info("根据主键查询渠道表结束 ：【5】【5】【5】【5】res5 = " + res5);
				
				if (res5.getRetCode().equals(RetCode.DB_ERROR)) {
					resultMap.put("retCode", RetCode.FAIL);
					resultMap.put("retMsg", "渠道开通列表查询失败");
					logger.info("查询渠道开通接口失败 ：【res5】【失败】 " + res5.getRetMsg());
					return JSONObject.fromObject(resultMap).toString();
				}
				
				if(res5.getRetCode().equals(RetCode.SUCCESS)){
					//获取查询到的渠道信息
					List<AppChannel> appChannellist = (List<AppChannel>)res5.getValue("appChannelList");
					logger.info("appChannellist  "+appChannellist);
					if(appChannellist.size()>0&&appChannellist!=null){
						AppChannel appChannel = appChannellist.get(0);
						//应用编号（店铺id）对应一个主产品号
						if (appChannel.getState().equals(4)) {
							logger.info("判断该店铺渠道开通为未签约状态===【】【】=====【】【】=====");
							String alipayRates = appChannel.getAlipayRates().toString();//支付宝费率
							String wecatRates = appChannel.getWecatRates().toString();//微信费率
							String storeId = storeInf.getStoreId().toString();//店铺Id
							String toreShortName = storeInf.getStoreShortName().toString();//店铺简称
							String merId = storeInf.getMerId().toString();//店铺主商户号
							String payeeMobileId = storeInf.getPayeeMobileId().toString();//手机号
							String productName=null; //主产品名称
							if(appChannel.getMainProductId().toString().equals(mainProductId)){
								productName="立马付收款";
							}
                         	payeeMobileId= payeeMobileId.replaceAll("(\\d{3})\\d{4}(\\w{4})","$1******$2");//脱敏
							result.put("storeId", storeId);
							result.put("toreShortName", toreShortName);
							result.put("productName",productName);
							result.put("merId", merId);
							result.put("bankMobileId", payeeMobileId);
					        result.put("alipayRates", alipayRates);
					        result.put("wecatRates", wecatRates);
					        resultMap.put("retCode",RetCode.SUCCESS);
					        resultMap.put("retMsg","此店铺未签约立马付产品");
					        resultMap.put("name",name);
					        resultMap.put("storeVo",result);
							return JSONObject.fromObject(resultMap).toString();
						}
					}
				}
				
			}
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "所有的店铺已签约");
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("retCode",RetCode.UNKNOWN);
			resultMap.put("retMsg", "首次签约初始化页面异常！");
			logger.error(String.format("==★★★★=====首次签约初始化页面异常，操作失败："), e);
		}
		logger.info("首次签约初始化页面接口结束==========>>>>>>|SignController|getStoreBySign");
		return JSONObject.fromObject(resultMap).toString();
	}
	
	
	/**
	 * 下发验证码短信接口
	 * @param request
	 * @param reponse
	 * @param bankMobileId
	 * @return
	 */
	@RequestMapping(value = "/send", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String send(HttpServletRequest request, HttpServletResponse reponse,String storeId) {
		logger.info("【调用下发短信验证码接口】开始");
		HttpSession session = request.getSession();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		// 店铺部署详情接口
		ReqMessage reqMe = ReqMessageUtil.makeSpReq();
		reqMe.getReqMap().put(CommonConsts.STOREID,storeId);
		ResMessage resMe = null;
		try {
			logger.info("【店铺部署详情接口】输入参数 ：ReqMessage=" + reqMe);
			resMe = storeInfServiceRemot.getStoreInfByPri(reqMe);
			logger.info("【店铺部署详情接口】输出参数:ResMessage=" + resMe);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(String.format("【店铺部署详情接口异常】"), e);
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433091);
		}

		// 获取店铺详情失败
		if (!RetCode.SUCCESS.equals(resMe.getRetCode())) {
			logger.info("【店铺部署详情接口失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433091);
		}
		// 获取店铺简称信息
		StoreInf storeInf = (StoreInf) resMe.getResMap().get(CommonConsts.STOREINF);
		String bankMobileId = storeInf.getPayeeMobileId();
		
		if(StringUtil.isEmpty(bankMobileId)){
			logger.info("获取手机号为空！");
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433061);
		}
		try {
			// ~~~~~~~~~~~~~~~~~~~~~~~~~调用下发短信息验证码接口~~~~~~~~~~~~~~~~~~~~~~~~~
			String productId = ValueConsts.PRODUCTID;
			logger.info("【下发短信验证码接口】入参" + CommonConsts.BANKMOBILEID + "：" + bankMobileId + CommonConsts.PRODUCTID+"：" + productId);
			Map<String, String> res = SmsCheckUtil.send(bankMobileId, productId);
			logger.info("【下发短信验证码接口】出参：" + res);
			if (res == null) { // 调用失败
				logger.info("下发短信验证码失败!");
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433062);
			}
			if (!res.get(CommonConsts.RETCODE).equals(RetCode.SUCCESS)) { // 失败
				logger.info("下发短信验证码错误!");
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433062);
			}
			session.setAttribute(CommonConsts.SMSVERIFYTRACE,StringUtil.trim(res.get(CommonConsts.SMSVERIFYTRACE)));
			session.setAttribute(CommonConsts.VERIFYCODE,StringUtil.trim(res.get(CommonConsts.VERIFYCODE)));
			session.setAttribute(CommonConsts.MOBILENO,StringUtil.trim(res.get(CommonConsts.MOBILENO)));
			resultMap.put(CommonConsts.BANKMOBILEID, bankMobileId); // 手机号
			resultMap.put(CommonConsts.TRACE, StringUtil.trim(res.get(CommonConsts.SMSVERIFYTRACE))); // 流水号
			resultMap.put(CommonConsts.VERIFYCODE, StringUtil.trim(res.get(CommonConsts.VERIFYCODE)));
			logger.info("下发短信验证码成功！");
			return ResultJsonUtil.resultJson(RetCode.SUCCESS, MsgConsts.I00433063 ,resultMap);
		} catch (Exception e) {
			logger.info("下发短信验证码失败!");
		}
		return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433062);
	}
	
	
	/**
	 * 确认签约
	 * @param session
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/receiver/updateStoreSign",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String updateStoreSign(String storeId,String bankMobileId,String verifyCode,HttpServletRequest request, HttpServletResponse response) throws Exception{		
		logger.info("确认签约接口开始==========>>>>>>|SignController|updateStoreSign");
		//String openid=request.getSession().getAttribute("openid").toString();//获取openid
		Map<String, Object> resultMap = new HashMap<String, Object>();
		HttpSession session=request.getSession();
		String openid = StringUtil.trim(session.getAttribute(CommonConsts.OPENID));	
		
		//店铺部署详情接口
		ReqMessage reqMe = ReqMessageUtil.makeSpReq();
		reqMe.getReqMap().put(CommonConsts.STOREID,storeId);
		ResMessage resMe = null;
		try {
			logger.info("【店铺部署详情接口】输入参数 ：ReqMessage=" + reqMe);
			resMe = storeInfServiceRemot.getStoreInfByPri(reqMe);
			logger.info("【店铺部署详情接口】输出参数:ResMessage=" + resMe);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(String.format("【店铺部署详情接口异常】"), e);
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433091);
		}

		// 获取店铺详情失败
		if (!RetCode.SUCCESS.equals(resMe.getRetCode())) {
			logger.info("【店铺部署详情接口失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433091);
		}
		// 获取店铺简称信息
		StoreInf storeInf = (StoreInf) resMe.getResMap().get(CommonConsts.STOREINF);
		bankMobileId = storeInf.getPayeeMobileId();
		
		
		
		logger.info("调用校验验证码信息接口，校验短信验证码====开始！====+++++++");
		String smsVerifyTrace=StringUtil.trim(session.getAttribute("smsVerifyTrace"));	//从session中获取流水号
//		String smsVerifyTrace = "6954809939364741";
		if(StringUtil.isEmpty(bankMobileId)){
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "获取手机号失败!");
			logger.info("获取前台手机号失败！");
			return  JSONObject.fromObject(resultMap).toString();
		}
		if(StringUtil.isEmpty(verifyCode)){
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "获取验证码失败!");
			logger.info("获取验证码失败！");
			return  JSONObject.fromObject(resultMap).toString();
		}
		if(StringUtil.isEmpty(smsVerifyTrace)){
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "获取流水号失败!");
			logger.info("获取流水号失败！");
			return  JSONObject.fromObject(resultMap).toString();
		}
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~检验短信验证码接口~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		Map<String,String> res=SmsCheckUtil.checksms(bankMobileId, smsVerifyTrace, verifyCode);
		if(res.isEmpty()||res==null){	//失败
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "校验验证码失败!");
			logger.info("校验验证码失败！");
			return  JSONObject.fromObject(resultMap).toString();
		}
		if(!res.get("retCode").equals(RetCode.SUCCESS)){		//验证码错误
			resultMap.put("retCode",RetCode.FAIL);
			resultMap.put("retMsg","验证码错误");
			logger.info("验证码错误！");
			return  JSONObject.fromObject(resultMap).toString();
		}
		logger.info("调用校验验证码信息接口，校验短信验证码======结束！====+++++++");
		
		if(StringUtil.isEmpty(openid)||openid==null){
			resultMap.put("retCode", RetCode.FAIL);
			logger.info("从session中openid获取失败！");
			return JSONObject.fromObject(resultMap).toString();
		}
		// 立马付产品编号
		String productId = PropertyUtil.getProperties(
				"umfWeChatPlat_appConf.properties").getProperty(
				"productId_impay");
		if (StringUtil.isEmpty(productId)) {
			resultMap.put("retCode", RetCode.FAIL);
			logger.info("获取property获取失败！");
			return JSONObject.fromObject(resultMap).toString();
		}
		// 立马付主产品编号
		String mainProductId = PropertyUtil.getProperties(
				"umfWeChatPlat_appConf.properties")
				.getProperty("mainProductId");
		if (StringUtil.isEmpty(mainProductId)) {
			resultMap.put("retCode", RetCode.FAIL);
			logger.info("获取mainProductId获取失败！");
			return JSONObject.fromObject(resultMap).toString();
		}
		
		try{
			
			String productId_add = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PRODUCTID_IMPAY_ADDED);
			// 渠道开通列表返回查询接口
			ReqMessage req1 = ReqMessageUtil.makeSpReq();
			req1.getReqMap().put("appSysId",storeId);
			req1.getReqMap().put("productIds","'"+productId+"','"+productId_add+"'");
			logger.info("根据主键查询渠道表开始 ：【1】【1】【1】【1】req1 = " + req1);
			ResMessage res1 =appChannelServiceRemote.getAppChannelListByProductids(req1);
			logger.info("根据主键查询渠道表结束 ：【1】【1】【1】【1】res1 = " + res1);
			if (!res1.getRetCode().equals(RetCode.SUCCESS)) {
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","渠道查询失败");
				logger.info("通过主键查询渠道开通接口失败 ：【res1】【失败】");
				return JSONObject.fromObject(resultMap).toString();
			}
			List<AppChannel> appChannellist = (List<AppChannel>)res1.getValue("appChannelList");
			String productIdTwo="";
			if(appChannellist.size()>0&&appChannellist!=null){
				AppChannel appChannel = appChannellist.get(0);
				productIdTwo = appChannel.getProductId();
				//应用编号（店铺id）对应一个主产品号
				if (appChannel.getState().equals(3)) {
					resultMap.put("retCode", RetCode.FAIL);
					resultMap.put("retMsg","该店铺渠道已经签约");
					logger.info("该店铺渠道已经开通===++++");
					return JSONObject.fromObject(resultMap).toString();
				}
			}
		
			logger.info("店铺部署详情 storeInf "+storeInf);
			//店铺状态
			String registerProcsState = storeInf.getRegisterProcsState();
			int parseInt = Integer.parseInt(registerProcsState);
			/*if(parseInt<5){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","提示你的店铺信息不全");
				logger.info("店铺部署详情接口  ：【res2】【提示你的店铺信息不全】" +res2.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}*/
			if(parseInt==10||parseInt==05){
				logger.info("店铺为未签约状态 ：=======++++++=======++++");
				
				//修改商户店铺详细信息接口(改为开通状态)
				ReqMessage req3 = ReqMessageUtil.makeSpReq();
				storeInf.setRegisterProcsState("07");
				
				logger.info("变更为‘自动开通待复查’插入操作记录 ------");				
				addJoinFlowForCheckMer(storeInf);
				
				storeInf.setIntime(null);
				storeInf.setModtime(null);
				Map<String, String> map = SaasPropertyUtil.javaBeanToMap(storeInf);
				req3.putAll(map);
				logger.info("修改商户店铺详细信息接口开始 ：【3】【3】【3】【3】req3=" + req3);
				ResMessage res3 = storeInfServiceRemot.updateStoreInf(req3);
				logger.info("修改商户店铺详细信息接口结束 ：【3】【3】【3】【3】res3=" + res3);
				//修改商户店铺失败
				if(!res3.getRetCode().equals(RetCode.SUCCESS)){
					resultMap.put("retCode", RetCode.FAIL);
					resultMap.put("retMsg","签约失败");
					logger.info("修改商户店铺接口失败  ：【res3】【失败】");
					return JSONObject.fromObject(resultMap).toString();
				}
			}
			
			logger.info("[saas平台]-开始开通商户各种配置-----start.");	
			AppChannel appChannel = appChannellist.get(0);
			ResMessage merJoin = registerMerJoin(storeId,appChannel,storeInf.getMerId());
			if(!RetCode.SUCCESS.equals(merJoin.getRetCode())){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","签约失败");
				return JSONObject.fromObject(resultMap).toString();
			}
			logger.info("[saas平台]-结束开通商户各种配置-----end.");
			
			//审核通过更新接口
			ReqMessage req4 = ReqMessageUtil.makeSpReq();
			req4.getReqMap().put("appSysId",storeId);
			req4.getReqMap().put("mainProductId",mainProductId);
			req4.getReqMap().put("state","3");
			req4.getReqMap().put("productId",productIdTwo);
			logger.info("审核通过更新接口开始 ：【4】【4】【4】【4】req4 = " + req4);
		    ResMessage res4 = appChannelServiceRemote.updateChannel(req4);
			logger.info("审核通过更新接口结束 ：【4】【4】【4】【4】res4 = " + res4);
			if(!res4.getRetCode().equals(RetCode.SUCCESS)){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","签约失败");
				logger.info("审核通过更新失败 ：【res4】【失败】");
				return JSONObject.fromObject(resultMap).toString();
			}else{
				resultMap.put("retCode", RetCode.SUCCESS);
				resultMap.put("retMsg",res4.getRetMsg());
				logger.info("审核通过更新成功 ：【res4】【成功】");
			}
			//判断是否配置银行卡
			//从session中获取主商户号
			String merId = StringUtil.trim(request.getSession().getAttribute("merId").toString());
			String isCard = banCard(merId);
			if("settleChoiceStore".equals(isCard)){
				resultMap.put("retCode", RetCode.CARDSUC);
				resultMap.put("retMsg","商户已绑卡");
			}else if("addBankCard".equals(isCard)){
				resultMap.put("retCode", RetCode.CARDFAIL);
				resultMap.put("retMsg","商户未绑卡");
			}else{
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg","签约成功查询是否绑卡失败");
				logger.info("签约成功查询是否绑卡失败");
				return JSONObject.fromObject(resultMap).toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(String.format("==★★★★★===确认签约接口异常，操作失败："), e);
			resultMap.put("retCode", RetCode.UNKNOWN);
			resultMap.put("retMsg","确认签约接口异常！");
		}
		logger.info("确认签约接口结束==========>>>>>>>|SignController|updateStoreSign");
		//测试
		logger.info("确认签约接口结束==========>>>>>>>|SignController|updateStoreSign" +JSONObject.fromObject(resultMap).toString());
		return JSONObject.fromObject(resultMap).toString();
	}
	//判断是否配置银行卡
	public String banCard(String merId){
		//已签约，判断绑卡状态
		logger.info("判断商户是否绑卡接口！");
		
		logger.info("session中获取merId:" + merId);
		if(!merId.equals("") && merId != null ){
			// 调用查询绑定银行卡信息接口
			logger.info("查询商户绑定银行卡接口：merId"+merId);
			com.umpay.operation.common.ReqMessage req = ReqMessageUtil.makeOpReq();
		    Map<String, Object> reqMap = new HashMap<String, Object>();	
		    reqMap.put("merId", merId);
		    reqMap.put("delayDays", 1);
		    reqMap.put("state", "2");
//		    reqMap.put("recvBankAccPro", "0");//对公对私
		    req.setReqMap(reqMap);
			com.umpay.operation.common.ResMessage ress;
			try {
				logger.info("查询商户绑定银行卡入参："+req);
				ress = edrawInfRemote.queryEdrewInf(req);
				logger.info("查询商户绑定银行卡出参："+ress);
			} catch (Exception e){
				logger.info("查询商户绑定银行卡信息接口exception");
				return "error";
			}	
			if(ress == null || !ress.getRetCode().equals(RetCode.SUCCESS)){   //查询失败
				logger.info("查询商户绑定银行卡信息接口失败");
				return "error";
			}
			EdrawInf edrawInfReData =(EdrawInf) ress.getResMap().get("edrawInf");
			logger.info("edrawInfReData================="+edrawInfReData);
			//判断是否有绑卡信息
			if(edrawInfReData !=null ){	//已经绑卡
				logger.info("判断绑卡成功商户已绑卡merId："+merId + "进入settleChoiceStore");
				return "settleChoiceStore";
			}else{	 //未绑卡
				logger.info("判断绑卡成功商户未绑卡merId："+merId + "进入addBankCard");
				return "addBankCard";
			}
		}
		logger.info("merId获取失败！");
		return "error";
		
	}
	
	/**
	 * 开通商户，步骤：*7、添加子商户产品关系 8、添加子商户业务协议关系 9、添加子商户支付产品与业务员协议关系
	 * *10、添加子商户签约产品、基础产品费率信息 11、添加子商户签约产品、基础产品风控信息  *12
	 * 
	 * @param appInfo
	 */
	@RequestMapping(value = "/receiver/registerMerJoin",produces="application/json;charset=UTF-8")
	@ResponseBody
	public ResMessage registerMerJoin(String storeId,AppChannel appChannel,String merId) throws Exception {
		
		ResMessage res = new ResMessage();
		String pProductId = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","productId_impay", "");
		String productIdBase = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","productId.saas.Base", "");
		if(StringUtils.isEmpty(pProductId)){
			res.setRetCode(RetCode.FAIL);
			res.setRetMsg("获取的立马付产品编号为空");
			return res;
		}
		if(StringUtil.isEmpty(productIdBase)){
			res.setRetCode(RetCode.FAIL);
			res.setRetMsg("获取的基础产品编号为空");
			return res;
		}
		//基础产品与立马付产品拼接
		StringBuffer s = new StringBuffer(pProductId);  
		 s.append("&");
		 s.append(productIdBase);
		String productIdsAll=s.toString();
		logger.info(String.format("==★========★==子商户注册操作，开始执行==★========★=="));
		String[] productIds = productIdsAll.split("&");
		try {
			
			logger.info(String.format("==★====★★★开始★★★★====★==子商户注册操作【7】：添加子商户产品关系"));
			for (String productID : productIds) {
				logger.info(String.format("==★====★★★★★★★★★★★====★==子商户注册操作【7】：添加子商户产品关系信息，产品编号：[%s]",productID));
				ResMessage resMessage4 = addMerProduct(storeId,productID);
				if(!RetCode.SUCCESS.equals(resMessage4.getRetCode())){
					res.setRetCode(RetCode.FAIL);
					res.setRetMsg(resMessage4.getRetMsg());
					return res;
				}
			}
			logger.info(String.format("==★====★★★★结束★★★====★==子商户注册操作【7】：添加子商户产品关系"));
			
			
			/*logger.info(String.format("==★====★★★★开始★★★★====★==子商户注册操作【8】：添加子商户业务协议关系"));
			ResMessage resMessage = addMerchantService(storeId);
			if(!RetCode.SUCCESS.equals(resMessage.getRetCode())){
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg(resMessage.getRetMsg());
				return res;
			}
			logger.info(String.format("==★====★★★★结束★★★★====★==子商户注册操作【8】：添加子商户业务协议关系"));*/
		
			/*logger.info(String.format("==★====★★★★★开始★★★★====★==子商户注册操作【9】：添加子商户支付产品与业务协议关系"));
			ResMessage resMessage1=addMerchantServiceAndProduct(storeId,productIdsAll);
			if(!RetCode.SUCCESS.equals(resMessage1.getRetCode())){
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg(resMessage1.getRetMsg());
				return res;
			}
			logger.info(String.format("==★====★★★★★结束★★★★====★==子商户注册操作【9】：添加子商户支付产品与业务协议关系"));*/

			
		   
		   
		   logger.info("==★====★★★★★开始★★★★★★====★==子商户注册操作【10】：立马付产品费率信息，产品编号："+productIds);
		    // 开通费率
			for (String productID : productIds) {
				logger.info(String.format("==★====★★★★★★★★★★★====★==子商户注册操作【10】：立马付产品费率信息，产品编号：[%s]",productID));
				
				ResMessage resMessage2 = allocationRate(productID,storeId,appChannel,merId,productIdBase);
				if(!RetCode.SUCCESS.equals(resMessage2.getRetCode())){
					res.setRetCode(RetCode.FAIL);
					res.setRetMsg(resMessage2.getRetMsg());
					return res;
				}
			}
			logger.info(String.format("==★====★★★★★结束★★★★★★====★==子商户注册操作【10】：立马付产品费率信息，产品编号："+productIds));

		   /* logger.info(String.format("==★====★★★★★开始★★★★★★====★==子商户注册操作【11】：立马付产品风控信息，产品编号：[%s]",productIds));
			//开通风控
			for (String productID : productIds) {
				logger.info(String
						.format("==★====★★★★★★★★★★★====★==子商户注册操作【11】：立马付产品风控信息，产品编号：[%s]",
								productID));
				ResMessage resMessage3 = configurationRiskControl(productID,storeId);
				if(!RetCode.SUCCESS.equals(resMessage3.getRetCode())){
					res.setRetCode(RetCode.FAIL);
					res.setRetMsg(resMessage3.getRetMsg());
					return res;
				}
			}
		    logger.info(String.format("==★====★★★★★结束★★★★★★====★==子商户注册操作【11】：立马付产品风控信息，产品编号：[%s]",productIds));
		*/	
			
			
			logger.info("==★====★★★★★开始★★★★====★==子商户注册操作【12】：配置商户与联动商户号的银商关系");
			ResMessage resMessage4 = addMerBank(storeId);
			if(!RetCode.SUCCESS.equals(resMessage4.getRetCode())){
				logger.error("==★====★★★★====★==主商户注册操作【12】：配置商户与联动商户号的银商关系，操作失败");
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg(resMessage4.getRetMsg());
				return res;
			}
			logger.info("==★====★★★★★结束★★★★====★==子商户注册操作【12】：配置商户与联动商户号的银商关系");
			
		    res.setRetCode(RetCode.SUCCESS);
			res.setRetMsg("子商户注册操作成功");
		    logger.info(String.format("==★========★==子商户注册操作，结束执行==★========★=="));
		} catch (Exception e) {
			logger.error(
					String.format("==★====★★★★★★★★====★==子商户注册操作：操作失败"),
					e);
			res.setRetCode(RetCode.FAIL);
			res.setRetMsg(res.getRetMsg());
		}
	    return res;
	}
	
	/**
	 * 子商户注册操作【7】：添加子商户产品关系
	 */
	public ResMessage addMerProduct(String storeId,String productId) throws Exception {
		logger.info("==★====子商户注册操作【7】：添加子商户产品关系==★====初始化产品参数====读取配置产品信息!");
		// 组装所有需要参数，读取配置产品信息
		ResMessage res= new ResMessage();
		com.umpay.operation.common.ReqMessage req1 = ReqMessageUtil.makeOpReq();
		com.umpay.operation.common.ResMessage res1 = null;
		req1.put("merId",storeId);	//商户ID
		req1.put("productId",productId);	//产品ID
		try {
			logger.info("==★====子商户注册操作【7】：通过商户ID和产品ID，查看商户产品的绑定关系==★====开始==req1=="+req1);
			res1 = merProductServiceRemote.getMerProductByKey(req1);
			logger.info("==★====子商户注册操作【7】：通过商户ID和产品ID，查看商户产品的绑定关系==★=====结束==res1="+res1.toString());
			
		} catch (Exception e) {
			logger.error(
					String.format("==★====★★★★★★====★==子商户注册操作【7】：查询子商户产品关系异常"),
					e);
			res.setRetCode(RetCode.FAIL);
			res.setRetMsg("查询子商户产品关系异常异常");
		}
		if(!"0000".equals(res1.getRetCode())){
			logger.info("==★====★★★★★★====★==子商户注册操作【7】：查询商户产品的绑定关系失败，返回错误信息：" + res1.toString());
			res.setRetCode(RetCode.FAIL);
			res.setRetMsg("查询子商户产品关系失败");
			return res;
		}
		//获取查到的商户产品
		MerProduct merProduct = (MerProduct) res.getResMap().get("merProduct");
		logger.info("merProduct========================="+merProduct);
		if(null==merProduct||"".equals(merProduct)){
			//调用CRM进行创建关系
			Map<String, Object> reqMap = new HashMap<String, Object>();
			String payElement = "";// 支付元素
			String ptype = productId.substring(3, 4); // 取产品号中付款标志位
			if (ptype.equals("5") || ptype.equals("7")) { // 信用卡无磁无密支付，信用卡无磁无密预授权
				payElement = "010203"; // 设置支付要素（cvv）
			} else if (ptype.equals("6")) { // 借记卡无磁无密支付
				payElement = "01";
			} else if (ptype.equals("4")) { // U付账户支付
				payElement = "";
			} else if ("P0000001".equals(productId) || "P0000002".equals(productId)) {
				payElement = "";
			} else {
				payElement = "";
			}
			reqMap.put("rpid", req1.getRpid());
			reqMap.put("funCode","QYZH");	//
			reqMap.put("merId",storeId);	//商户ID
			reqMap.put("accTypeTag", "2");	//开户类型
			reqMap.put("productId", productId);	//产品ID
			reqMap.put("playelements", payElement);
			reqMap.put("RegPointTag", "40");	//开通渠道
			reqMap.put("sendSMS", "2");
			Map<String, Object> crmResult = null;
			String retCode = "";
			try {
				XStream xstream = new XStream(new DomDriver());
				// URL配置文件取
				String url = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","upay.crm.account.url", "");	//获取商户产品绑定关系URL
				logger.info("==★====子商户注册操作【7】：添加子商户产品关系==★开始====开始添加商户产品关系");
				//调用受理注销用户标识接口
				crmResult = (Map<String, Object>)HttpHelper.getResObjPost(url, xstream, reqMap);
				logger.info("==★====子商户注册操作【7】：添加子商户产品关系==★结束====开始添加商户产品关系crmResult"+crmResult);
				if(crmResult==null || crmResult.isEmpty()) {
					logger.info("==★====★★★★★★====★==子商户注册操作【7】：请求CRM系统失败:添加商户产品的绑定关系失败");
					res.setRetCode(RetCode.FAIL);
					res.setRetMsg("添加子商户产品绑定关系失败");
					return res;
				}
				retCode = (String) crmResult.get("retCode");
				if (!"0000".equals(retCode)){
					logger.info(String
							.format("==★====★★★★★★★====★==子商户注册操作【7】：请求CRM系统失败:添加商户产品的绑定关系失败"));
					res.setRetCode(RetCode.FAIL);
					res.setRetMsg("添加子商户产品绑定关系失败");
					return res;
				}
				res.setRetCode(RetCode.SUCCESS);
				res.setRetMsg("添加子商户产品绑定关系成功");
				return res;
			} catch (Exception e) {
				logger.info("==★====★★★★★★====★==子商户注册操作【7】：请求CRM系统失败:添加商户产品的绑定关系失败  "+e.toString());
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg("添加子商户产品绑定关系异常");
				return res;
			}
			
		}
		res.setRetCode(RetCode.SUCCESS);
		res.setRetMsg("子商户产品已经绑定过关系");
		return res;
	}

	
	/**
	 * 子商户注册操作【8】：添加子商户业务协议关系
	 * 
	 * @return
	 * @throws Exception
	 */
	public ResMessage addMerchantService(String storeId) throws Exception {
		String BProductId ="B2002001";//业务产品号
		String state ="2";
		
		ResMessage res= new ResMessage();
	    com.umpay.operation.common.ResMessage resMessage=null;
		com.umpay.operation.common.ReqMessage req = ReqMessageUtil.makeOpReq();

		// 校验请求参数，应用的子商户是从来没有录入过系统的，该出的校验参数可以取消
		// boolean what = this.isExistsByMerIdAndBusProId(BProductId);

		try {
			req.put(XmlData.BUSINESS_PROTOCOL_ID,
					this.createMbAgreementId(storeId, BProductId)); // 协议号
			logger.info("==★====★★★★★★★====★==子商户注册操作【8】：生成【商户业务协议号】成功。");
		} catch (Exception e) {
			logger.error("==★====★★★★★★★====★==子商户注册操作【8】：生成【商户业务协议号】失败。",
					e.getMessage());
		}

		String effTime = CommonUtils
				.dateFormat(new SimpleDateFormat("yyyyMMdd").format(System
						.currentTimeMillis()));
		// 此处增加50年
		String expireTime = CommonUtils.dateFormat(new SimpleDateFormat(
				"yyyyMMdd").format((System.currentTimeMillis()) + 1000000000));
		req.put(XmlData.TAKE_EFFECT_TIME, effTime);
		req.put(XmlData.EXPIRE_TIME, expireTime);
		req.put(XmlData.IN_USER, "saas");
		req.put(XmlData.MODUSER, "saas");
		req.put(XmlData.STATE, state);
		req.put(XmlData.REGISTER_CHANNEL_ID, "Saas");
		req.put(XmlData.MER_ID, storeId);
		req.put(XmlData.BUSINESS_PRODUCT_ID, BProductId);
		logger.info(String.format("==★====★★★★开始★★★★====★==子商户注册操作【8】：添加子商户业务协议关系"));
		//resMessage = protocolServiceRemote.save(req);
		logger.info(String.format("==★====★★★★结束★★★★====★==子商户注册操作【8】：添加子商户业务协议关系"));
		
		// 校验返回码
		if (!RetCode.SUCCESS.equals(resMessage.getRetCode())) {
			logger.info("==★====★★★★★★★====★==子商户注册操作【8】：添加【子商户业务协议关系】失败:"
					+ resMessage.getRetMsg());
			res.setRetCode(RetCode.FAIL);
			res.setRetMsg("添加子商户业务协议关系失败");
		}else{
			res.setRetCode(RetCode.SUCCESS);
			res.setRetMsg("添加子商户业务协议关系成功");
			logger.info(String
					.format("==★====★★★★★★★★====★==子商户注册操作【8】：添加子商户业务协议关系执行成功！！！"));
		}
		return res;
	}
	
	/**
	 * 创建【商户业务协议号】
	 * 
	 * @param merId
	 *            商户号
	 * @param businessProductId
	 *            业务产品号
	 * @return 【商户业务协议号】
	 * @throws Exception
	 */
	private String createMbAgreementId(String merId, String businessProductId)
			throws Exception {
		logger.info("生成【商户业务协议号】  ------start。");
		if (CommonUtils.isEmpty(merId)
				|| CommonUtils.isEmpty(businessProductId))
			return null;

		StringBuilder protocolId = new StringBuilder();
		try {
			// 商户号-业务产品-日期-4位流水
			protocolId.append(merId).append("-");
			protocolId.append(businessProductId).append("-");
			protocolId.append(DateTimesUtil.date8()).append("-");
			protocolId.append(SequenceUtil.getSeq("merBusiAgr", 4));
			logger.info("生成商户业务协议号：" + protocolId.toString() + "------end。");
			return protocolId.toString();
		} catch (Exception e) {
			logger.error("生成【商户业务协议号】  ------end。", e);
			throw new Exception("生成商户业务协议号失败！", e);
		}
	}

	/**
	 * 添加【商户业务协议与支付产品关系&判断是否已添加过商户业务协议与支付产品关系】
	 * @return
	 * @date 2017-02-09
	 */
	public ResMessage addMerchantServiceAndProduct(String storeId,String productIdsAll) {

		String BProductId ="B2002001";//业务产品号
		String state ="2";
		
		ResMessage res= new ResMessage();
		com.umpay.operation.common.ResMessage resMessage=null;
		com.umpay.operation.common.ReqMessage req = ReqMessageUtil.makeOpReq();
	
		try {
			// 查询已经配置的商户业务列表
			req.put("merId", storeId);
			req.put("businessProductId", BProductId);
			logger.info(String
					.format("==★====★★★★★★★★★====★==子商户注册操作【9】：查询商户业务协议号== start "));
			//resMessage = protocolServiceRemote.list(req);
			logger.info(String
					.format("==★====★★★★★★★★★====★==子商户注册操作【9】：查询商户业务协议号== end "));
			List<Protocol> resultList = (List<Protocol>) resMessage.getValue("resultList");
			if (null == resultList || !(resultList.size() > 0)) {
				logger.info(String.format("==★====★★★★★★★★★====★==子商户注册操作【9】：查询商户业务协议号失败 "));
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg("查询商户业务协议号失败");
				return res;
			}
			logger.info(String.format("==★====★★★★★★★★★====★==子商户注册操作【9】：查询商户业务协议号== 执行成功 "));

			String merchantBusinessProtocolId = null;
			for (Protocol protocol : resultList) {
				merchantBusinessProtocolId = protocol.getMBAgreementId();
			}
			
			String[] result = null;
			//是否添加过协议与产品关系操作
			if (StringUtils.isNotBlank(merchantBusinessProtocolId)) {
				//产品编号数组
				String[] PproductIds = productIdsAll.split("&");
				List<String> productIdList = new ArrayList<String>();
				logger.info("判断【商户是否已添加商户业务协议与支付产品关系】------start。");
				if (null != PproductIds && PproductIds.length > 0) {
					//遍历产品编号
					for (String productId : PproductIds) {
						if (!productIdList.contains(productId.trim().toUpperCase())) {
							//输入参
							Map<String, Object> qryMap = new HashMap<String, Object>();
							qryMap.put("state", state);
							qryMap.put("mbAgreementId", merchantBusinessProtocolId);
							qryMap.put("pproductId",productId);
							
							//List<BusiAgreementPro> list = busiAgreementProRemote.findBusiAgreementProList(qryMap);
							List<String> list=new ArrayList<String>();
							if(list.size()==0||list==null){
								//没有添加过业务协议与支付产品关系的产品编号
								productIdList.add(productId.trim().replaceAll("\n", "")
										.toUpperCase());
							}
						}
					}
				}
				logger.info("判断【商户是否已添加商户业务协议与支付产品关系】------end。");
				logger.info("productIdList======================"+productIdList);
				if (productIdList.size() > 0) {
					result = (String[]) productIdList.toArray(new String[productIdList
							.size()]);
				}
				logger.info("result============================="+result);
			}

			logger.info("==★====★★★★★★★★★====★==子商户注册操作【9】：添加【商户业务协议与支付产品关系】------ start。");
		/*	String loginUser = "saas";
			List<BusiAgreementPro> busiAgreementProList = new ArrayList<BusiAgreementPro>();
			// 装配请求参数
			if (CommonUtils.isNotEmpty(result)) {
				for (int index = 0, length = result.length; index < length; index++) {
					BusiAgreementPro busiAgreementPro = new BusiAgreementPro();
					busiAgreementPro.setPproductId(result[index]);//支付产品号
					busiAgreementPro.setBproductId(BProductId);//业务产品号
					if (CommonUtils.isNotEmpty(merchantBusinessProtocolId))//商户业务协议号
						busiAgreementPro
								.setMbAgreementId(merchantBusinessProtocolId);
					if (CommonUtils.isNotEmpty(state))
						busiAgreementPro.setState(BusiAgreementPro.STATE_VALID);//状态
					if (null != loginUser) {
						busiAgreementPro.setInstUser(loginUser);
						busiAgreementPro.setModUser(loginUser);
					}
					busiAgreementProList.add(busiAgreementPro);
				}
				logger.info("==★====★★★★★开始★★★★====★==子商户注册操作【9】：添加【商户业务协议与支付产品关系】请求业管平台参数个数："
						+ busiAgreementProList.toString());
				busiAgreementProRemote.batchAddBusiAgreementPro(busiAgreementProList);
				logger.info("==★====★★★★★结束★★★★====★==子商户注册操作【9】：添加【商户业务协议与支付产品关系】执行成功！！！");
				res.setRetCode(RetCode.SUCCESS);
				res.setRetMsg("添加商户业务协议与支付产品关系成功");
			}
*/			res.setRetCode(RetCode.SUCCESS);
			res.setRetMsg("添加商户业务协议与支付产品关系都已存在");
			
		} catch (Exception e) {
			logger.error(
					"==★====★★★★★★★★★====★==子商户注册操作【9】：添加【商户业务协议与支付产品关系】执行成功！！！",
					e.getMessage());
			res.setRetCode(RetCode.FAIL);
			res.setRetMsg("添加商户业务协议与支付产品关系失败");
		}	
		return res;
	}

	/**
	 * 子商户注册操作【10】： 配置费率
	 */
	public ResMessage allocationRate(String productID,String storeId,AppChannel appChannel,String merId,String productIdBase){

		String[] split = productIdBase.split("&");
		List<String> list=Arrays.asList(split);//基础产品
		logger.info("基础产品list"+list);
		logger.info("【10】：添加产品费率信息，产品编号：" + productID);
		ResMessage res= new ResMessage();
		String url = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","ACC_FEE_URL", "");
		Map<String, Object> params = new HashMap<String, Object>();
		ReqMessage r = ReqMessageUtil.makeSpReq();
		String rpid = r.getRpid();
		params.put("rpid", rpid);
		params.put("reqDate", r.getReqDate());
		params.put("reqTime", r.getReqTime());
		params.put("merId",merId);
		params.put("subMerId",storeId);
		params.put("startDate", r.getReqDate());// 起始日期
		params.put("productId", productID);// 产品号
		
		// 配置公共参数
		params.put("modId","spapply");//
		//params.put(XmlData.OPERUSER, "spapply");//操作人
		//params.put(XmlData.FEETYPE, "11");// 费率类型
		//params.put(XmlData.FEEVALUE, "0.06");// 费率值
		
		params.put("actSettlType","2");//记账结算类型
		params.put("feeRateType","11");//费率类型
		params.put("minFee","1");//保底手续费
		params.put("maxFee","0");//封顶手续费
		params.put("isReturn","0");//是否退换手续费
		
		if("P15Y0002".equals(productID)||"P15X0001".equals(productID)||"P15Y0023".equals(productID)){
			if(appChannel!=null){
				Integer wecatRates = appChannel.getWecatRates();
				if(wecatRates==null){
					res.setRetCode(RetCode.FAIL);
					res.setRetMsg("费率值不能为空");
					return res;
				}else{
					Integer wecatRates2 = appChannel.getWecatRates();
					double doubleValue = wecatRates2.doubleValue();
					double doubleValue2=doubleValue/1000/100;
					String result = String .format("%.6f",doubleValue2);
					Double valueOf = Double.valueOf(result);
					if(valueOf<1){
						params.put("feeRateValue",result);//微信费率值
					}else{
						res.setRetCode(RetCode.FAIL);
						res.setRetMsg("费率值不能大于等于一");
						return res;
					}
				}
			}else{
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg("产品值不能为空");
				return res;
			}
		}else if("P15Y0003".equals(productID)||"P15X0002".equals(productID)||"P15Y0024".equals(productID)){
			if(appChannel!=null){
				Integer alipayRates = appChannel.getAlipayRates();
				if(alipayRates==null){
					res.setRetCode(RetCode.FAIL);
					res.setRetMsg("费率值不能为空");
					return res;
				}else{
					Integer alipayRates2 = appChannel.getAlipayRates();
					double doubleValue = alipayRates2.doubleValue();
					double doubleValue2=doubleValue/1000/100;
					String result = String .format("%.6f",doubleValue2);
					Double valueOf = Double.valueOf(result);
					if(valueOf<1){
						params.put("feeRateValue",result);//支付宝费率值
					}else{
						res.setRetCode(RetCode.FAIL);
						res.setRetMsg("费率值不能大于等于一");
						return res;
					}
				}
			}else{
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg("产品值不能为空");
				return res;
			}
		}else if(list.contains(productID)){
			params.put("feeRateValue","0");	//费率值
		}else{
			res.setRetCode(RetCode.FAIL);
			res.setRetMsg("该产品值没有对应的费率配置");
			return res;
		}
		try {
			logger.info("【配置付款费率】httpPostForm2Xml请求数据：params"+params+ "url="+ url);	
			Map<String, Object> rescon = HttpUtil.httpPostForm2Xml(url, params);
			logger.info("【配置付款费率】httpPostForm2Xml返回结果：",rescon);
			if(null==rescon||StringUtil.isEmpty((String) rescon.get(XmlData.RETCODE))){
				logger.info("【配置付款费率】失败,返回值rescon="+rescon);
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg("配置费率失败");
				return res;
			}
			if(RetCode.SUCCESS.equals(StringUtil.trim(rescon.get(XmlData.RETCODE)))){
				logger.info("【配置付款费率】成功！");			
				res.setRetCode(RetCode.SUCCESS);
			}else if("00170020".equals(StringUtil.trim(rescon.get(XmlData.RETCODE)))){
				logger.info("【配置付款费率】已存在，不需要配置！");		
				res.setRetCode(RetCode.SUCCESS);
			}else{
				logger.info("【配置付款费率】失败,返回码"+rescon.get(XmlData.RETCODE));
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg((String)rescon.get(XmlData.RETMSG));
			}
			logger.info("【配置付款费率】返回结果res="+res);
		}catch (Exception e) {
			logger.error("调用配置费率接口异常"+e);
			res.setRetCode(RetCode.UNKNOWN);
			res.setRetMsg("调用配置费率接口异常"+e.getMessage());
			return res;
		}
		return res;
	}

	/**
	 * desc: 配置风控
	 * author：zhangxichao
	 * @param request
	 * @param response
	 * @param session
	 * @param model
	 * @return
	 */

	public ResMessage configurationRiskControl(String productID,String storeId){
		logger.info("【11】：添加产品风控信息=-----【start】======产品编号：" + productID);
		ResMessage res= new ResMessage();
		String url="";
		Map<String, Object> params = new HashMap<String, Object>();
		ReqMessage r = ReqMessageUtil.makeSpReq();
		String rpid = r.getRpid();
		params.put(XmlData.LIMIT_RPID, rpid);
		/*params.put("reqDate", r.getReqDate());
		params.put("reqTime", r.getReqTime());*/
		params.put(XmlData.LIMIT_MERID,storeId);
		params.put(XmlData.LIMIT_PRODUCTID, productID);// 产品号
		
		params.put(XmlData.INDUSTRYID,"1000");//
		
		params.put(XmlData.TAG_ID,"1");//
		params.put(XmlData.ONCE_AMOUNT_LIMIT,"500000");//单笔限额 
		params.put(XmlData.HOUR_AMOUNT_LIMIT,"-1");//小时限额 
		params.put(XmlData.DAY_AMOUNT_LIMIT,"200000");//日限额 
		params.put(XmlData.MONTH_AMOUNT_LIMIT,"-1");//月限额 
		params.put(XmlData.HOUR_FREQ_LIMIT,"-1");//小时限额次
		params.put(XmlData.DAY_FREQ_LIMIT,"-1");//日限次
		params.put(XmlData.MONTH_FREQ_LIMIT,"-1");//月限次
	
		try {
			 logger.info("商户【配置风控】请求参数：params"+params);
			// Map<String, Object> rescon = HttpUtil.httpPostXStream2XStream(url, params,"utf-8");
			 RequestUtil requestUtil = new RequestUtil();
			 Map<String, Object> rescon= (Map<String, Object>) requestUtil.sendRequestForPost(url, params);	
			
			 logger.info("商户【配置风控】响应：rescon"+rescon);
			if(null==rescon||StringUtil.isEmpty((String) rescon.get(XmlData.RETCODE))){
				logger.info("商户【配置风控】失败,返回值rescon="+rescon);
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg("配置风控失败");
				return res;
			}
			if(RetCode.SUCCESS.equals(StringUtil.trim(rescon.get(XmlData.RETCODE)))){
				logger.info("【配置风控】成功！");			
				res.setRetCode(RetCode.SUCCESS);
			}else{
				logger.info("【配置风控】失败,返回码"+rescon.get(XmlData.RETCODE));
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg((String)rescon.get(XmlData.RETMSG));
			}
			logger.info("【配置风控】返回结果res="+res);
			
		}catch (Exception e) {
			logger.error("调用配置风控接口异常"+e);
			res.setRetCode(RetCode.UNKNOWN);
			res.setRetMsg("调用配置风控接口异常"+e.getMessage());
			return res;
		}
		return res;
	}
	
	
	/**
	 * 添加子商户支付服务商信息
	 * @param storeId
	 * @return
	 */
	public ResMessage addMerBank(String storeId){
		String bankId[] = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties", "BANKID_SAAS", "").split("&");	//支付服务商编号
		String bankMerId[] = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties", "BANKMERID_SAAS", "").split("&");	//平台在机构的商户号
		com.umpay.operation.common.ReqMessage req1 = ReqMessageUtil.makeOpReq();
		com.umpay.operation.common.ResMessage res1 = null;
		ResMessage res= new ResMessage();
		for (int i = 0; i < bankId.length; i++) {
			/**
			 * 查询商户是否配置过支付服务商
			 */
			req1.put("merId",storeId);	//商户ID
			req1.put("bankId",bankId[i]);	//支付服务商编号
			try {
				res1 = bankInfServiceRemote.queryMerbankByMerIdAndBankId(req1);
			
			} catch (Exception e) {
				logger.error("查看子商户支付服务商信息异常"+e);
				res.setRetCode(RetCode.UNKNOWN);
				res.setRetMsg("查看子商户支付服务商信息异常"+e.getMessage());
				return res;
			}
			if (!"0000".equals(res1.getRetCode())) {
				logger.info("==★====★====★==子商户注册操作【12】：查看子商户支付服务商信息失败");
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg("查询子商户支付服务商信息失败");
				return res;
			}
			
			List<MerBankInf> merBankInfs = (List<MerBankInf>) res1.getResMap().get("merBankInfList");
			if (merBankInfs.size() < 1) {
				req1.put("bankInfs","[{'bankMerId':'" + bankMerId[i] +"','state':'2','merId':'" + storeId + "','bankId':'" + bankId[i] + "'}]");
				try {
					res1 = bankInfServiceRemote.insertMerBankInfBatch(req1);
				
				} catch (Exception e) {
					logger.info("==★====★====★==子商户注册操作【12】：添加子商户支付服务商信息失败");
					res.setRetCode(RetCode.UNKNOWN);
					res.setRetMsg("添加子商户支付服务商信息异常"+e.getMessage());
					return res;
				}
				if (!"0000".equals(res1.getRetCode())) {
					logger.info("==★====★====★==子商户注册操作【12】：添加子商户支付服务商信息失败");
					res.setRetCode(RetCode.FAIL);
					res.setRetMsg("添加子商户支付服务商信息失败");
					return res;
				}else if("0000".equals(res1.getRetCode())){
					logger.info("==★====★====★==子商户注册操作【12】：添加子商户支付服务商信息成功    'merId':'" + storeId + "','bankId':'" + bankId[i] + "'");
					res.setRetCode(RetCode.SUCCESS);
					res.setRetMsg("添加子商户支付服务商信息成功");
				}
				
			}else{
				logger.info("==★====★====★==子商户注册操作【12】：添加子商户支付服务商信息已存在    'merId':'" + storeId + "','bankId':'" + bankId[i] + "'");
				res.setRetCode(RetCode.SUCCESS);
				res.setRetMsg("子商户支付服务商信息已存在");
			}
		}
	    return res;
	}
	/**
	 *  变更为‘自动开通待复查'插入操作记录
	 * @param storeInf	店铺详情
	 * @param res	 
	 * @return
	 */
	public com.umpay.operation.common.ResMessage addJoinFlowForCheckMer(StoreInf storeInf){
		
		com.umpay.operation.common.ResMessage res = null;
		com.umpay.operation.common.ReqMessage req = ReqMessageUtil.makeOpReq();
		try {
			
		req.put(CommonConsts.MERUNIFORMID,storeInf.getStoreId());	//商户唯一标识
		req.put("handleState","0");	//申请处理状态
		req.put("handleState","0");	//申请处理状态   0-初始 1-完成
		req.put("handleStep","自动开通待复查");	//处理节点  中文描述
		req.put("handleRole","00");	//处理人角色：00系统自动；01财务； 02运营； 03客服 ；04商户 ；99其他		
		logger.info("----#---------#--变更为‘自动开通待复查’插入操作记录，请求参数：--#---------#--" + req);
		res = joinFlowServiceRemote.add(req);
		logger.info("----#---------#--变更为‘自动开通待复查’插入操作记录，返回参数：--#---------#--" + res);
		} catch (Exception e) {
			logger.error(storeInf.getStoreId() +"----#---------#--变更为‘自动开通待复查’插入操作记录异常--#---------#--" , e);		
		}
		return res;
	}
	

}
